package org.luo.lan.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
 * @Auther: luobiao
 * @Date: 2020/9/19 09:15
 * @Description:
 */
@Slf4j
public class WatchServiceUtil {

    public static void watchDirChange(String dirName, Consumer<List<String>> consumer) {
        Assert.fielExist(new File(dirName),"监听的目录不存在！");
        Runnable run=()->{
            WatchService watchService= null;
            try {
                watchService = FileSystems.getDefault().newWatchService();
                Path path=Paths.get(dirName);
                path.register(watchService,StandardWatchEventKinds.ENTRY_MODIFY);
            } catch (IOException ex) {
                log.error("文件监听失败！ex={}",ex);
                Thread.interrupted();
            }

            while (!Thread.currentThread().isInterrupted()) {  //一直监听，直到线程中断
                WatchKey watchKey = null;
                try {
                    watchKey = watchService.take();
                } catch (InterruptedException ex) {
                    log.error("文件监听线程中断！ex={}", ex);
                    Thread.currentThread().interrupt();
                }
                List<String> changeFileList = new ArrayList<>();
                for (WatchEvent event : watchKey.pollEvents()) {
                    if (StandardWatchEventKinds.ENTRY_MODIFY == event.kind()) {
                        changeFileList.add(String.valueOf(event.context()));
                    }
                }
                consumer.accept(changeFileList);
                watchKey.reset();
            }
        };
        Thread thread = new Thread(run,"file-watch-service");
        thread.setDaemon(true);//需要设置为守护线程，不然在在netty中的线程都结束后还是无法结束应用
        thread.start();
    }
}
